﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Collections.Generic;

namespace PKEngine
{
	/// <summary>
	/// Main surface of engine.
	/// </summary>
	public class PKMainSurface : PKSurface, IDisposable
	{
		#region Singleton
		private static PKMainSurface _sharedMainSurface;

		public static PKMainSurface SharedMainSurface
		{
			get
			{
				if (_sharedMainSurface == null)
				{
					_sharedMainSurface = new PKMainSurface();
				}
				return _sharedMainSurface;
			}
		}
		#endregion

		#region Private Fields
		private PictureBox bindingMainScreen;
		private Bitmap bufferBitmap;
		private PKSurface bufferSurface;
		private Stack<Rectangle> clippingRects;
		#endregion

		#region Public Properties
		public Rectangle SceneRect { get; set; }

		public override Rectangle ClippingRect
		{
			get
			{
				return (Rectangle)(clippingRects.Peek());
			}
		}
		#endregion

		#region Initialization
		private PKMainSurface()
			: base(new Size(PKConfig.SharedConfig.ScreenWidth, PKConfig.SharedConfig.ScreenHeight))
		{
			this.SceneRect = new Rectangle(0, 0, PKConfig.SharedConfig.ScreenWidth, PKConfig.SharedConfig.ScreenHeight);
			this.clippingRects = new Stack<Rectangle>();
		}

		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (bufferBitmap != null)
			{
				bufferBitmap.Dispose();
			}
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Bind to MainScreen picture box.
		/// </summary>
		/// <param name="mainScreen">The picture box</param>
		/// <returns>True if the function is finished successfully</returns>
		public bool BindToMainScreen(PictureBox mainScreen)
		{
			Debug.Assert(mainScreen != null, "PKMainSurface.BindToMainScreen: Argument cannot be null.");

			bool isSuccessful;

			try
			{
				this.bindingMainScreen = mainScreen;

				switch (this.PixelFormat)
				{
					case PKPixelFormat.Argb1555:
						this.bufferBitmap = new Bitmap(this.bindingMainScreen.Width, this.bindingMainScreen.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
						break;
					case PKPixelFormat.Rgb565:
						this.bufferBitmap = new Bitmap(this.bindingMainScreen.Width, this.bindingMainScreen.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
						break;
					case PKPixelFormat.Rgb555:
						this.bufferBitmap = new Bitmap(this.bindingMainScreen.Width, this.bindingMainScreen.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
						break;
					case PKPixelFormat.Argb4444:
						this.bufferBitmap = new Bitmap(this.bindingMainScreen.Width, this.bindingMainScreen.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
						break;
				}

				if (this.bindingMainScreen.Width != this.ContentSize.Width || this.bindingMainScreen.Height != this.ContentSize.Height)
				{
					this.bufferSurface = new PKSurface(new Size(this.bindingMainScreen.Width, this.bindingMainScreen.Height));
				}

				this.bindingMainScreen.Image = this.bufferBitmap;

				isSuccessful = true;
			}
			catch
			{
				isSuccessful = false;
			}

			return isSuccessful;
		}

		/// <summary>
		/// Show buffer bitmap on MainScreen picture box.
		/// </summary>
		/// <returns>True if the function is finished successfully</returns>
		public bool ShowOnMainScreen()
		{
			Debug.Assert(bindingMainScreen != null, "PKMainSurface.ShowOnMainScreen: Must bind to main screen.");
			Debug.Assert(bufferBitmap != null, "PKMainSurface.ShowOnMainScreen: Must create a background buffer.");

			bool isSuccessful;

			byte[] temp;
			int length = this.bindingMainScreen.Width * this.bindingMainScreen.Height;
			PKSurface surface = null;
			if (this.bufferSurface != null)
			{
				PKAlpha.SharedAlpha.BltStretch(this.bufferSurface, this.bufferSurface.ClippingRect, this, base.ClippingRect);
				surface = this.bufferSurface;
			}
			else
			{
				surface = this;
			}
			try
			{
				BitmapData data = this.bufferBitmap.LockBits(new Rectangle(0, 0, PKConfig.SharedConfig.ScreenWidth, PKConfig.SharedConfig.ScreenHeight), ImageLockMode.WriteOnly, this.bufferBitmap.PixelFormat);
				switch (this.PixelFormat)
				{
					case PKPixelFormat.Argb1555:
					case PKPixelFormat.Rgb565:
					case PKPixelFormat.Rgb555:
						// Copy data directly.
						temp = new byte[length * 2];
						for (int i = 0; i < length; i++)
						{
							byte[] bytes = BitConverter.GetBytes(surface.Data[i]);
							temp[i * 2] = bytes[0];
							temp[i * 2 + 1] = bytes[1];
						}
						System.Runtime.InteropServices.Marshal.Copy(temp, 0, data.Scan0, length * 2);
						break;
					case PKPixelFormat.Argb4444:
						// Convert from 16bpp to 24bpp.
						temp = new byte[length * 3];
						for (int i = 0; i < length; i++)
						{
							uint argb8888 = surface.Data[i];
							// From AAAARRRRGGGGBBBB to AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB.
							argb8888 = ((argb8888 & 0xF00) << 12) | // R
									   ((argb8888 & 0xF0) << 8) | // G
									   ((argb8888 & 0xF) << 4) | // B
									   0xF0F0F;

							byte[] bytes = BitConverter.GetBytes(argb8888);
							temp[i * 3 + 0] = bytes[0];
							temp[i * 3 + 1] = bytes[1];
							temp[i * 3 + 2] = bytes[2];
						}
						System.Runtime.InteropServices.Marshal.Copy(temp, 0, data.Scan0, length * 3);
						break;
				}
				this.bufferBitmap.UnlockBits(data);

				if (bindingMainScreen != null)
				{
					bindingMainScreen.Invoke(new MethodInvoker(delegate() { bindingMainScreen.Refresh(); }));
				}

				isSuccessful = true;
			}
			catch
			{
				isSuccessful = false;
			}

			return isSuccessful;
		}

		/// <summary>
		/// Pop a ClippingRect.
		/// </summary>
		public void PopClippingRect()
		{
			clippingRects.Pop();
		}

		/// <summary>
		/// Push a ClippingRect.
		/// </summary>
		/// <param name="newRect">new clipping rectangle</param>
		public void PushClippingRect(Rectangle newRect)
		{
			this.ClipRect(ref newRect);
			clippingRects.Push(newRect);
		}

		/// <summary>
		/// Clear all ClippingRects.
		/// </summary>
		public void ClearClippingRects()
		{
			clippingRects.Clear();
			clippingRects.Push(new Rectangle(0, 0, PKConfig.SharedConfig.ScreenWidth, PKConfig.SharedConfig.ScreenHeight));
		}

		/// <summary>
		/// Save current screen to a image file.
		/// </summary>
		/// <param name="filePath">Target file path</param>
		public void ScreenShot(string filePath)
		{
			try
			{
				bufferBitmap.Save(filePath, ImageFormat.Png);
			}
			catch (Exception exception)
			{
				MessageBox.Show(exception.Message);
			}
		}

		/// <summary>
		/// Clone current screen to a surface.
		/// </summary>
		/// <returns></returns>
		public PKSurface ScreenClone()
		{
			PKSurface surface = new PKSurface(new Size(PKConfig.SharedConfig.ScreenWidth, PKConfig.SharedConfig.ScreenHeight));
			int length = PKConfig.SharedConfig.ScreenWidth * PKConfig.SharedConfig.ScreenHeight;
			for (int i = 0; i < length; i++)
			{
				surface.Data[i] = this.Data[i];
			}
			return surface;
		}
		#endregion
	}
}
